#include <Arduino.h>
#include <BluetoothSerial.h>

#define LED 22


//*蓝牙模块的数据包结构
typedef struct
{
	uint8_t Head;
	uint8_t data_1;
    uint32_t data2;     //!因为定义在setup中的变量不能被loop调用
	uint8_t data_2[5];  //一个整形数据,前四位位传输的数据位，[4]是校验位
    uint32_t data3;     //!因为定义在setup中的变量不能被loop调用
	uint8_t data_3[5];  //一个浮点型32位,前四位位传输的数据位，[4]是校验位
	uint8_t Low8;       //-再增加结构体时，低8位计算中要加上增加的[4]第5个数组
	uint8_t End;
}Data_TypeDef;
Data_TypeDef Data_Stucture;
BluetoothSerial SerialBT;

//!i为整形，byte为结构体的成员变量
void Int_to_Byte(uint32_t i,uint8_t *byte)
{
	byte[3] = (i & 0xFF000000) >> 24;
	byte[2] = (i & 0x00FF0000) >> 16;
	byte[1] = (i & 0x0000FF00) >> 8;
	byte[0] = (i & 0x000000FF);
	byte[4] = ((byte[0]+byte[1]+byte[2]+byte[3])&0xff);//!校验位，用在主程序中的低8位校验
}
void SerialBT_Send_int(uint32_t i,uint8_t *array)
{
    Int_to_Byte(i,array);
    SerialBT.write(array[0]);delayMicroseconds(50);
    SerialBT.write(array[1]);delayMicroseconds(50);
    SerialBT.write(array[2]);delayMicroseconds(50);
    SerialBT.write(array[3]);delayMicroseconds(50);
}

void setup()
{

    Serial.begin(115200);
    SerialBT.begin("ESP32_BT"); // 如果没有参数传入则默认是蓝牙名称是: "ESP32"
    pinMode(LED,OUTPUT);


    Data_Stucture.Head=0xA5;
	Data_Stucture.data_1=-123;
    Data_Stucture.data2=-123;
	Data_Stucture.End=0x5A;

}

void loop()
{
    if(Serial.available())
    {
        Data_Stucture.data2=Serial.read();
        digitalWrite(LED,HIGH);
    }
    SerialBT.write(Data_Stucture.Head);
    SerialBT.write(Data_Stucture.data_1);
    SerialBT_Send_int(Data_Stucture.data2,Data_Stucture.data_2);
    Data_Stucture.Low8=((Data_Stucture.data_1+Data_Stucture.data_2[4])&0xff);
    SerialBT.write(Data_Stucture.Low8);
    SerialBT.write(Data_Stucture.End);

    Data_Stucture.data2++;
    digitalWrite(LED,LOW);
    delay(500);
    Serial.print(Data_Stucture.data2);
    // Serial.print(Data_Stucture.data_1);
    // Serial.print("\n");
    // Serial.print(Data_Stucture.data2);
    // Serial.print("\n");
    // Serial.print("--------------------");
}
